import random
from time import sleep
import time
import win32api
import pandas as pd
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
import win32con

from login import LoginTaobao
from pyquery import PyQuery as Pq


class GetGoods:

    fileName: None
    driver: WebDriver
    total_pages: int = 0
    cur_page_num: int = 1
    page_text: WebElement
    goods_items: list = []
    infos: list = []

    def __init__(self, username, password, good_name, pages=1, condition=""):
        self.good_name = good_name
        self.condition = condition
        self.pages = pages
        user = LoginTaobao(username, password)
        user.login()
        self.driver = user.driver

    def get_goods_info(self):
        print("搜索商品")
        # 重置导出数据集合
        self.infos = []

        self.driver.get(
            f"https://s.taobao.com/search?q={self.good_name}" + f"&{self.condition}")

        sleep(3)
        # 获取商品总页数
        self.total_pages = int(self.driver.find_element
                               (By.XPATH, '//*[@id="mainsrp-pager"]/div/div/div/div[1]').text.split(" ")[1])

    def cyclic_print_good_info(self):

        for good in self.goods_items:
            title = good.find(".title").text()
            price = good.find(".price").text()
            pay_nums = good.find(".deal-cnt").text()
            shop_name = good.find(".shopname").text()
            location = good.find(".location").text()
            img_url = good.find(".pic .img").attr("data-src")
            detail_url = good.find(".pic-link").attr("data-href")
            shopLink = good.find(".shop .J_ShopInfo").attr("href")

            dict = {
                '标题': title,
                '价格': price,
                '店铺': shop_name,
                '购买人数': pay_nums,
                '地点': location,
                '商品详情页': 'https:' + detail_url,
                '店铺链接': 'https:' + shopLink,
                '图片链接': 'https:' + img_url
            }
            self.infos.append(dict)
            print(dict)

        self.cur_page_num += 1

    def clean_goods_data(self):
        html = self.driver.page_source
        doc = Pq(html)
        page_text = self.driver.find_element(
            By.XPATH, '//*[@id="mainsrp-pager"]/div/div/div/div[2]/input')
        self.goods_items[:] = doc(
            "#mainsrp-itemlist > div > div > div:nth-child(1) .item").items()
        self.cyclic_print_good_info()
        page_text.clear()
        page_text.send_keys(self.cur_page_num)
        self.driver.find_element(
            By.XPATH, '//*[@id="mainsrp-pager"]/div/div/div/div[2]/span[3]').click()
        
        random_number = random.randint(3, 10)
        sleep(random_number)

    def get_goods_data(self):
        self.get_goods_info()
        while self.cur_page_num <= self.pages <= self.total_pages:
            self.clean_goods_data()

        self.data_to_csv()

        # 提醒OK消息框
        win32api.MessageBox(
            0, f"采集信息完成, 生成文件路径为: {self.fileName}", "提醒", win32con.MB_OK)

    def data_to_csv(self):
        self.fileName = 'd:/info-' + time.strftime('%Y%m%d%H%M%S') + '.csv'

        fieldnames = [
            '标题', '价格', '店铺', '购买人数', '地点', '商品详情页', '店铺链接', '图片链接']
        toCsv = pd.DataFrame(columns=fieldnames, data=self.infos)
        toCsv.to_csv(self.fileName, index=False, encoding='utf_8_sig')


def main():
    GetGoods('18010911042', 'Azhangrui=7970', "手机", pages=1).get_goods_data()


if __name__ == "__main__":
    main()
